<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\SendWechatTemplate;
use App\Models\Book;
use App\Models\SellOrder;
use App\Models\SellOrderExpressInfo;
use App\Models\SellOrderItem;
use App\Models\User;
use App\Models\UserAccountRecord;
use App\Services\UserCouponService;
use Illuminate\Http\Request;
use EasyWeChat;

class SellOrderController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('check_admin_login');
    }

    public function index(Request $request)
    {
        $page                         = intval($request->get('page',1));
        $page                         = max($page ,1);
        $page_size                    = intval($request->get('limit',10));
        $no                           = trim($request->get('no'));
        $start_time                   = intval($request->get('start_time'));
        $end_time                     = intval($request->get('end_time'));
        $state                        = intval($request->get('state'));//0全部 -2=用户主动取消 -1=审核未通过 1=提交成功  2=审核通过 3=快递已取货 4=平台确认收货  5=已打款
        $nickname                     = trim($request->get('nickname'));
        $user_id                      = intval($request->get('user_id'));

        $builder = SellOrder::query()->with(['user','sell_order_items']);

        if(!empty($no))
        {
            $no = '%'.$no.'%';
            $builder->where('no','like',$no);
        }

        if(!empty($start_time))
        {
            $builder->where('created_at','>=',$start_time);
        }

        if(!empty($nickname))
        {
            $builder->where('user_nickname','like','%'.$nickname.'%');
        }

        if(!empty($end_time))
        {
            $builder->where('created_at','<=',$end_time);
        }

        if(!empty($state))
        {
            $builder->where('state',$state);
        }

        if(!empty($user_id))
        {
            $builder->where('user_id',$user_id);
        }

        $columns = ['id','user_id','no','state','created_at','total_price','actual_price'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);


        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'            => $item->id,
                    'user_id'       => $item->user_id,
                    'no'            => $item->no,
                    'created_at'    => date('Y-m-d H:i:s',$item->created_at),
                    'state'         => $item->state,
                    'total_price'   => $item->total_price,
                    'actual_price'  => $item->actual_price,
                    'user_nickname' => $item->user->wechat_nickname,
                    'user_avatar'   => $item->user->wechat_avatar,
                    'books_num'     => count($item->sell_order_items),
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(Request $request)
    {
        $sell_order_id = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }
        $order = SellOrder::query()->with(['sell_order_items','user','sell_order_items.book','sell_order_items.book.parent_catgeory'])->where('id',$sell_order_id)->first();
        //dd($order);

        $books = [];

        $unpass_price = 0;
        $unpass_num = 0;
        $medium_price = 0;
        $medium_num = 0;
        $first_pass_num = 0;
        $first_unpass_num = 0;
        $medium_price_total = 0;

        if(!empty($order->sell_order_items))
        {
            foreach ($order->sell_order_items as $v)
            {
                if($v->state == 1)
                {
                    if(in_array($v->type,[3,4,5,6,7,8]))
                    {
                        $medium_num++;
                        $medium_price += round($v->book_recyle_price - $v->actual_recyle_price,1);
                        $medium_price_total += round($v->actual_recyle_price,1);
                    }
                }
                else
                {
                    //未通过审核
                    $unpass_price += $v->book_recyle_price;
                    $unpass_num ++;
                }

                if($v->first_check_state == 1)
                {
                    $first_pass_num ++;
                }
                else
                {
                    $first_unpass_num ++;
                }
                $books[] = [
                    'order_item_id'         => $v->id,
                    'book_id'               => $v->book_id,
                    'book_title'            => $v->book_title,
                    'book_image'            => $v->book_image,
                    'book_author'           => $v->book_author,
                    'book_recyle_price'     => $v->book_recyle_price,
                    'actual_recyle_price'   => $v->actual_recyle_price,
                    'first_check_state'     => $v->first_check_state,
                    'state'                 => $v->state,
                    'type'                  => $v->type,
                    'reason'                => $v->reason,
                    'book_isbn'             => $v->book->isbn,
                    'book_old_price'        => $v->book->old_price,
                    'book_total_stock'      => $v->book->total_stock,
                    'book_parent_catgeory'  => optional($v->book->parent_catgeory)->title ? optional($v->book->parent_catgeory)->title : '',
                ];
            }
        }


        //获取物流信息
        $row = SellOrderExpressInfo::query()->where('sell_order_id',$sell_order_id)->orderBy('id','desc')->first();
        $express_info = [];
        if(!empty($row))
        {
            $express_info = [
                'sell_order_id' => $row->sell_order_id,
                'express_no'    => $row->express_no,
                'state'         => $row->state,
                'trces'         => array_reverse(json_decode($row->traces,true)),
                'express_name'  => '顺丰速运',
            ];
        }


        $medium_price = round($medium_price,1);
        $unpass_price = round($unpass_price,1);
        $medium_price_total = round($medium_price_total,1);
        //dd($express_info);
        $result = [
            'id'                            => $order->id,
            'no'                            => $order->no,
            'state'                         => $order->state,  //-2=用户主动取消 -1=审核未通过 1=提交成功  2=审核通过 3=快递已取货 4=平台确认收货  5=已打款
            'shipper_code'                  => $order->shipper_code,
            'express_no'                    => $order->express_no,  //快递单号
            'deliver_address_province'      => $order->deliver_address_province,
            'deliver_address_city'          => $order->deliver_address_city,
            'deliver_address_area'          => $order->deliver_address_area,
            'deliver_address_detail'        => $order->deliver_address_detail,
            'deliver_name'                  => $order->deliver_name,
            'deliver_mobile'                => $order->deliver_mobile,
            'total_price'                   => $order->total_price, //总估价
            'actual_price'                  => $order->actual_price,  //最终收入
            'unpass_price'                  => $unpass_price,  //未通过审核扣除的金额
            'unpass_num'                    => $unpass_num,//未通过审核的数量
            'medium_price'                  => $medium_price,   //品相中等扣除的金额
            'medium_num'                    => $medium_num, //品相中等数量
            'medium_price_total'            => $medium_price_total, //品相中等价格最终价格总和
            'cancel_user'                   => $order->cancel_user,
            'is_overtime'                   => $order->is_overtime,
            'first_pass_num'                => $first_pass_num,  //初审通过数量
            'first_unpass_num'              => $first_unpass_num,  //初审未通过数量
            'express_time'                  => $order->express_time ? date('Y-m-d H:i:d',$order->express_time) : '',  //预约快递上门时间
            'created_at'                    => $order->created_at ? date('Y-m-d H:i:d',$order->created_at) : '',  //订单提交时间
            'check_time'                    => $order->check_time ? date('Y-m-d H:i:d',$order->check_time) : '',  //审核通过时间
            'express_get_time'              => $order->express_get_time ? date('Y-m-d H:i:d',$order->express_get_time) : '',  //快递取货时间
            'platform_confirm_time'         => $order->platform_confirm_time ? date('Y-m-d H:i:d',$order->platform_confirm_time) : '',  //平台收货时间
            'platform_success_time'         => $order->platform_success_time ? date('Y-m-d H:i:d',$order->platform_success_time) : '',  //审核打款时间
            'cancel_time'                   => $order->cancel_time ? date('Y-m-d H:i:d',$order->cancel_time) : '',  //取消时间
            'first_not_pass_time'           => $order->first_not_pass_time ? date('Y-m-d H:i:d',$order->first_not_pass_time) : '',  //审核不通过时间
            'user_nickname'                 => $order->user->wechat_nickname,
            'user_avatar'                   => $order->user->wechat_avatar,
            'books_total'                   => count($books),
            'books'                         => $books,
            'express_info'                  => $express_info,  //快递信息
        ];
        return $this->ok($result);
    }

    /**
     * 审核打款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function check(Request $request)
    {
        $books          = trim($request->get('books'));  //[{"book_id":16,"state":1,"type":1,"reason":""},{"book_id":5,"state":2,"type":0,"reason":"就是不通过"}]
        $sell_order_id  = intval($request->get('sell_order_id'));

        if(empty($sell_order_id) || empty($books))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 4)
        {
            return $this->err(1,200,'','状态错误');
        }

        $book_arr = json_decode($books,true);
        if(empty($book_arr) || !is_array($book_arr))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::query()->where('id',$order->user_id)->first();
        \DB::beginTransaction();    //主事务
        try {
            $actual_price = 0;
            $number1 = 0;
            $number2 = 0;
            foreach ($book_arr as $v)
            {
                $item = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->where('book_id',$v['book_id'])->first();
                if($item)
                {
                    if($v['state'] == 1)
                    {
                        $actual_recyle_price = 0;
                        if($v['type'] == 1)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 1;
                            Book::query()->where('id',$v['book_id'])->increment('new_book_stock');
                        }
                        elseif($v['type'] == 2)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 1;
                            Book::query()->where('id',$v['book_id'])->increment('good_book_stock');
                        }
                        elseif($v['type'] == 3)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 0.75;
                            Book::query()->where('id',$v['book_id'])->increment('medium_book_stock');
                        }
                        elseif($v['type'] == 4)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 0.75;
                            Book::query()->where('id',$v['book_id'])->increment('medium_book_stock2');
                        }
                        elseif($v['type'] == 5)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 0.75;
                            Book::query()->where('id',$v['book_id'])->increment('medium_book_stock3');
                        }
                        elseif($v['type'] == 6)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 0.75;
                            Book::query()->where('id',$v['book_id'])->increment('medium_book_stock4');
                        }
                        elseif($v['type'] == 7)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 0.75;
                            Book::query()->where('id',$v['book_id'])->increment('medium_book_stock5');
                        }
                        elseif($v['type'] == 8)
                        {
                            $actual_recyle_price = $item->book_recyle_price * 0.75;
                            Book::query()->where('id',$v['book_id'])->increment('medium_book_stock6');
                        }
                        Book::query()->where('id',$v['book_id'])->increment('total_stock');
                        $data = [
                            'state'               => 1,
                            'type'                => $v['type'],
                            'actual_recyle_price' => round($actual_recyle_price,1)
                        ];

                        $actual_price += $actual_recyle_price;
                        $number1++;
                    }
                    else
                    {
                        $number2++;
                        $data = [
                            'state'     => $v['state'],
                            'reason'    => $v['reason'],
                        ];
                    }

                    $item->update($data);
                }
            }

            $actual_price = round($actual_price,1);
            $sms = app('easysms');
            try {
                $sms->send($order->deliver_mobile,[
                    'template' => 'SMS_175572854',
                    'data' => [
                        'name'      => $order->deliver_name,
                        'money'     => $actual_price,
                        'number1'   => $number1,
                        'number2'   => $number2,
                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                dd($message);
            }

            //使用异步队列
            $job_params = [
                'user_id'           => $user->id,
                'template_id'       => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                'sell_order_id'     => $order->id,
                'number1'           => $number1,
                'number2'           => $number2,
                'actual_price'      => $actual_price,
                'type'              => 2,
            ];
            dispatch(new SendWechatTemplate($job_params));

            /*$officialAccount = EasyWeChat::officialAccount(); // 公众号
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $first = "卖书订单已审核完成\r\n"."您卖的书其中{$number1}本审核通过，{$number2}本审核不通过，总收入{$actual_price}元。\r\n";
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                    'url'  => '',
                    'data' => [
                        'first'         => $first,
                        'OrderSn'       => $order->no,
                        'OrderStatus'   => '审核完成，已打款'."\r\n",
                        'remark'        => '在个人主页「我的余额」可进行书费提现。如需取回被拒收的书，请在72小时内在卖书订单详情选择拒书取回。点击本消息可直接进入。'
                    ],
                ]);
            }*/


            $order->update([
                'actual_price'          => $actual_price,
                'state'                 => 5,
                'platform_success_time' => $this->time,
            ]);

            if($actual_price > 0)
            {
                //用户账户余额
                $user->increment('account',$actual_price);
                //账户余额记录
                UserAccountRecord::create([
                    'type'    => 2,
                    'account' => $actual_price,
                    'remark'  => '卖书收入',
                    'user_id' => $order->user_id,
                ]);
            }

            if(!empty($user->recommend_user_id) && !$user->is_recommend_coupon)
            {
                //给推荐人发送红包奖励
                $userCouponService = new UserCouponService();
                $userCouponService->getCoupon($user->recommend_user_id,1);

                $user->update(['is_recommend_coupon'=>1]);

                //给推荐人发送微信消息
                //使用异步队列
                /*$job_params = [
                    'user_id'           => $user->recommend_user_id,
                    'template_id'       => 'IZIf7iWG7W_yZuapB6bSfo4do97wzB_JIEH6O9CyAiQ',
                    'coupon_type'       => 1,
                    'type'              => 2,  //下单买书
                    'wechat_nickname'  => $user->wechat_nickname,
                ];
                dispatch(new SendWechatTemplate($job_params));*/

                $officialAccount = EasyWeChat::officialAccount(); // 公众号
                $recommend_user = User::find($user->recommend_user_id);
                $wechat_user = \DB::table('wechat_users')->where('unionid',$recommend_user->unionid)->first();
                if(!empty($wechat_user))
                {
                    $openid = $wechat_user->openid;

                    $coupon = \DB::table('coupons')->where('type',1)->first();
                    $first = "获得红包提醒\r\n"."你邀请的好友{$user->wechat_nickname}成功下单卖书，你获得一个".$coupon->amount."元买书抵扣红包，订单满".$coupon->order_price."元可用，有效期".$coupon->days."天。\r\n";
                    $officialAccount->template_message->send([
                        'touser'        => $openid,
                        'template_id'   => 'IZIf7iWG7W_yZuapB6bSfo4do97wzB_JIEH6O9CyAiQ',
                        'url'  => '',
                        'miniprogram' => [
                            'appid'     => config('wechat.mini_program.default.app_id'),
                            'path'      => '/pages/red-package/red-package'
                        ],
                        'data' => [
                            'first'      => $first,
                            'keyword1'   => $coupon->amount,
                            'keyword2'   => date('Y-m-d H:i:s'),
                            'keyword3'   => $coupon->amount."元买书抵扣红包\r\n",
                            'remark'     => '点击查看红包详情'
                        ],
                    ]);
                }
            }

            \DB::commit();
            return $this->ok([]);
        } catch (\Exception $e) {
            \DB::rollBack();
            //echo $e->getMessage();
            return $this->err(1,200,$e->getMessage(),'订单审核不通过操作失败');
        }
    }

    /**
     * 订单审核不通过 v2版本
     */
    public function unchecked(Request $request)
    {
        $sell_order_id  = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }
        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误');
        }

        //短信
        $sms = app('easysms');
        try {
            $sms->send($order->deliver_mobile,[
                'template' => 'SMS_175061213',
                'data' => [
                    'name'      => $order->deliver_name,
                ],
            ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $message = $exception->getException('aliyun')->getMessage();
            dd($message);
        }

        //消息发送
        //发送模板消息
        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$order->user_id)->first();
        $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
        if(!empty($wechat_user))
        {
            $openid = $wechat_user->openid;

            $first = "卖书订单已关闭\r"."很抱歉，您的卖书订单未通过审核，该订单包含多本流通率较低的书，您可以尝试再次扫码卖书，我们已更新了该书的回收状态。\r";
            $officialAccount->template_message->send([
                'touser'        => $openid,
                'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                'url'  => '',
                'miniprogram' => [
                    'appid'     => config('wechat.mini_program.default.app_id'),
                    'path'  => '/pages/sale/order/order-detail/order-detail?id='.$order->id,
                ],
                'data' => [
                    'first'         => $first,
                    'OrderSn'       => $order->no,
                    'OrderStatus'   => '审核未通过，订单关闭'."\r\n",
                    'remark'        => '您可在小程序内查看订单详情。'
                ],
            ]);
        }

        $order->update([
            'state'                 => -1,
            'is_closed'             => 1,
            'updated_at'            => $this->time,
            'first_not_pass_time'   => $this->time,
        ]);

        return $this->ok([]);
    }

    /**
     * 订单审核通过 v2版本
     */
    public function checked(Request $request)
    {
        $books          = trim($request->get('books'));  //[{"book_id":10,"is_success":1},{"book_id":10,"is_success":1}]
        $sell_order_id  = intval($request->get('sell_order_id'));
        if(empty($sell_order_id) || empty($books))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误');
        }

        $book_arr = json_decode($books,true);
        if(empty($book_arr) || !is_array($book_arr))
        {
            return $this->err(1,200,'','参数错误');
        }

        //$sell_order_books_num = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->count();

        //构造在线下单提交信息
        $eorder = [];
        $eorder["ShipperCode"] = "SF";
        $eorder["OrderCode"] = $order->no;
        $eorder["PayType"] = 2;  //1-现付，2-到付，3-月结，4-第三
        $eorder["ExpType"] = 2;
        $eorder["StartDate"] = date('Y-m-d H:i:s',$order->express_time);

        $sender = [];
        $sender["Name"] = $order->deliver_name;
        $sender["Mobile"] = $order->deliver_mobile;
        $sender["ProvinceName"] = $order->deliver_address_province;
        $sender["CityName"] = $order->deliver_address_city;
        $sender["ExpAreaName"] = $order->deliver_address_area;
        $sender["Address"] = $order->deliver_address_detail;

        $receiver = [];
        $receiver["Name"] = "快鱼二手书（请发特惠件或大件）";
        $receiver["Mobile"] = "15888825922";
        $receiver["ProvinceName"] = "浙江省";
        $receiver["CityName"] = "杭州市";
        $receiver["ExpAreaName"] = "余杭区";
        $receiver["Address"] = "万科未来城二期21-1-2302";

        $commodityOne = [];
        $commodityOne["GoodsName"] = "图书";
        $commodity = [];
        $commodity[] = $commodityOne;

        $eorder["Sender"] = $sender;
        $eorder["Receiver"] = $receiver;
        $eorder["Commodity"] = $commodity;

        //调用在线下单
        $jsonParam = json_encode($eorder, JSON_UNESCAPED_UNICODE);
        $jsonResult = $this->_submitOrder($jsonParam);

        //解析在线下单返回结果
        $result = json_decode($jsonResult, true);
        if(($result['Success'] && $result['ResultCode'] == 100))
        {
            $number = 0;
            foreach ($book_arr as $v)
            {
                $first_check_state = 1;
                if(!$v['is_success'])
                {
                    $first_check_state = 0;
                    $number++;
                }

                $item = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->where('book_id',$v['book_id'])->first();
                if($item)
                {
                    $item->update([
                        'first_check_state' => $first_check_state
                    ]);
                }
            }

            $order->update([
                'state'             => 2,
                'is_express'        => 1,
                'express_no'        => $result['Order']['LogisticCode'],
                'shipper_code'      => $result['Order']['ShipperCode'],  //快递公司编码
                'express_order_no'  => $result['Order']['OrderCode'],
                'check_time'        => $this->time,
            ]);

            if($number)
            {
                //有不通过的
                $sms = app('easysms');
                try {
                    $sms->send($order->deliver_mobile,[
                        'template' => 'SMS_175573453',
                        'data' => [
                            'name' => $order->deliver_name,
                            'number' => $number,
                            'time' => date('Y-m-d H:i',$order->express_time),
                        ],
                    ]);
                } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                    $message = $exception->getException('aliyun')->getMessage();
                    dd($message);
                }

                //发送模板消息
                $officialAccount = EasyWeChat::officialAccount(); // 公众号
                $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$order->user_id)->first();
                $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                if(!empty($wechat_user))
                {
                    $openid = $wechat_user->openid;

                    $express_time = date('Y-m-d H:i',$order->express_time);
                    $first = "卖书订单通过审核（其中有{$number}本不收，请不要将其寄过来）\r"."顺丰快递将于你预约的时间：{$express_time}免费上门取书。在预约的时间前1小时内您会收到顺丰的短信，请留意短信通知。\r";
                    $officialAccount->template_message->send([
                        'touser'        => $openid,
                        'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                        'url'  => '',
                        'miniprogram' => [
                            'appid'     => config('wechat.mini_program.default.app_id'),
                            'path'  => '/pages/sale/order/order-detail/order-detail?id='.$order->id,
                        ],
                        'data' => [
                            'first'         => $first,
                            'OrderSn'       => $order->no,
                            'OrderStatus'   => '已安排快递上门取书'."\r\n",
                            'remark'        => '在订单详情中可查看不需要邮寄的书'
                        ],
                    ]);
                }

            }
            else
            {
                //全部通过
                $sms = app('easysms');
                try {
                    $sms->send($order->deliver_mobile,[
                        'template' => 'SMS_175533598',
                        'data' => [
                            'name' => $order->deliver_name,
                            'time' => date('Y-m-d H:i',$order->express_time),
                        ],
                    ]);
                } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                    $message = $exception->getException('aliyun')->getMessage();
                    dd($message);
                }

                $officialAccount = EasyWeChat::officialAccount(); // 公众号
                $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$order->user_id)->first();
                $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                if(!empty($wechat_user))
                {
                    $openid = $wechat_user->openid;

                    $express_time = date('Y-m-d H:i',$order->express_time);
                    $first = "卖书订单通过审核\r"."顺丰快递将于你预约的时间：{$express_time}免费上门取书。在预约的时间前1小时内您会收到顺丰的短信，请留意短信通知。\r";
                    $officialAccount->template_message->send([
                        'touser'        => $openid,
                        'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                        'url'  => '',
                        'miniprogram' => [
                            'appid'     => config('wechat.mini_program.default.app_id'),
                            'path'  => '/pages/sale/order/order-detail/order-detail?id='.$order->id,
                        ],
                        'data' => [
                            'first'         => $first,
                            'OrderSn'       => $order->no,
                            'OrderStatus'   => '已安排快递上门取书'."\r\n",
                            'remark'        => '请提前将要卖的书打包好，如需更改快递上门时间，请在快递员联系你时，直接告知快递员新的上门取件时间即可。'
                        ],
                    ]);
                }
            }





            return $this->ok([]);
        }

        return $this->err(1,200,'','预约快递失败');
    }

    public function firstCheck(Request $request)
    {
        $books          = trim($request->get('books'));  //[{"book_id":10,"is_success":1},{"book_id":10,"is_success":1}]
        $sell_order_id  = intval($request->get('sell_order_id'));
        if(empty($sell_order_id) || empty($books))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误');
        }

        $book_arr = json_decode($books,true);
        if(empty($book_arr) || !is_array($book_arr))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$order->user_id)->first();
        \DB::beginTransaction();    //主事务
        try {

            $number = 0;
            foreach ($book_arr as $v)
            {
                $first_check_state = 1;
                if(!$v['is_success'])
                {
                    $first_check_state = 0;
                    $number++;
                }

                $item = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->where('book_id',$v['book_id'])->first();
                if($item)
                {
                    $item->update([
                        'first_check_state' => $first_check_state
                    ]);
                }
            }

            $order->update([
                'state'                 => -1,
                'is_closed'             => 1,
                'updated_at'            => $this->time,
                'first_not_pass_time'   => $this->time,
            ]);

            //发送短信
            $sms = app('easysms');
            try {
                $sms->send($order->deliver_mobile,[
                    'template' => 'SMS_163437073',
                    'data' => [
                        'name'      => $order->deliver_name,
                        'number'    => $number,
                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                dd($message);
            }

            //发送模板消息
            $officialAccount = EasyWeChat::officialAccount(); // 公众号
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $total = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->count();
                $number2 = $total - $number;
                $first = "卖书订单已关闭\r\n"."很抱歉，您的卖书订单未通过审核，其中{$number2}本支持回收，{$number}本不支持回收，请根据原因调整后重新下单吧。\r\n"."原因：该书籍流通率较低，暂时不支持回收\r\n";
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                    'url'           => '',
                    'miniprogram'   => [
                        'appid'     => config('wechat.mini_program.default.app_id'),
                        'path'  => '/pages/sale/order/order-detail/order-detail?id='.$order->id,
                    ],
                    'data' => [
                        'first'         => $first,
                        'OrderSn'       => $order->no,
                        'OrderStatus'   => '审核未通过，订单关闭'."\r\n",
                        'remark'        => '点击“详情”可查看订单详情。'
                    ],
                ]);
            }

            \DB::commit();
            return $this->ok([]);
        } catch (\Exception $e) {
            \DB::rollBack();
            //echo $e->getMessage();
            return $this->err(1,200,$e->getMessage(),'订单审核不通过操作失败');
        }
    }

    public function confirm(Request $request)
    {
        $sell_order_id  = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 3)
        {
            return $this->err(1,200,'','状态错误');
        }

        $order->update([
            'state'                     => 4,
            'platform_confirm_time'     => $this->time,
        ]);

        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$order->user_id)->first();
        $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
        if(!empty($wechat_user))
        {
            $openid = $wechat_user->openid;

            $first = "平台已收货，待验收打款\r\n"."您卖的图书，平台已经收到，我们将在1-3个工作日内完成对书的检验审核，请耐心等待。\r";
            $officialAccount->template_message->send([
                'touser'        => $openid,
                'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                'url'  => '',
                'miniprogram' => [
                    'appid'     => config('wechat.mini_program.default.app_id'),
                    'path'  => '/pages/sale/order/order-detail/order-detail?id='.$order->id,
                ],
                'data' => [
                    'first'         => $first,
                    'OrderSn'       => $order->no,
                    'OrderStatus'   => '平台已收货，待验收'."\r\n",
                    'remark'        => '用卖书到账的余额买书可享受8.7折优惠，卖书越多，买书就越省钱哦。'
                ],
            ]);
        }


        return $this->ok([]);
    }

    public function cancel(Request $request)
    {
        $sell_order_id  = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 2)
        {
            return $this->err(1,200,'','状态错误');
        }

        $params = [
            'ShipperCode'   => $order->shipper_code,
            'OrderCode'     => $order->express_order_no,
            'LogisticCode'  => $order->express_no,
        ];
        //调用在线取消订单
        $jsonParam = json_encode($params, JSON_UNESCAPED_UNICODE);
        $jsonResult = $this->_cancelOrder($jsonParam);

        //解析返回结果
        $result = json_decode($jsonResult, true);
        //print_r($result);die;
        if($result['Success'] && $result['ResultCode'] == 100)
        {

        }
        $order->update([
            'state'             => -2,
            'updated_at'        => $this->time,
            'is_closed'         => 1,
            'cancel_user'       => 1,
            'cancel_time'       => $this->time,
            'cancel_sf_result'  => json_encode($result),
        ]);
        return $this->ok([]);
        //return $this->err(1,200,'','订单无法取消');
    }

    public function test(Request $request)
    {
        $sell_order_id  = intval($request->get('sell_order_id'));
        $order = SellOrder::query()->where('id',$sell_order_id)->first();

        //发送模板消息
        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$order->user_id)->first();
        $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
        if(!empty($wechat_user))
        {
            $openid = $wechat_user->openid;

            $express_time = date('Y-m-d H:i',$order->express_time);
            $first = "卖书订单通过审核，待快递上门取书\r"."顺丰快递将于你预约的时间：{$express_time}免费上门取书。在预约的时间前1小时内您会收到顺丰的短信，请留意短信通知。\r";
            $officialAccount->template_message->send([
                'touser'        => $openid,
                'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                'url'  => '',
                'miniprogram' => [
                    'appid'     => config('wechat.mini_program.default.app_id'),
                    'path'  => '/pages/sale/order/order-detail/order-detail?id='.$order->id,
                ],
                'data' => [
                    'first'         => $first,
                    'OrderSn'       => $order->no,
                    'OrderStatus'   => '已安排快递上门取书'."\r\n",
                    'remark'        => '如需修改快递上门时间或订单信息，请取消订单后再重新下单，可在订单详情页进行操作。'
                ],
            ]);
        }
    }

    public function ordersSf(Request $request)
    {
        $sell_order_id  = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误');
        }

        //构造在线下单提交信息
        $eorder = [];
        $eorder["ShipperCode"] = "SF";
        $eorder["OrderCode"] = $order->no;
        $eorder["PayType"] = 2;  //1-现付，2-到付，3-月结，4-第三
        $eorder["ExpType"] = 2;
        $eorder["StartDate"] = date('Y-m-d H:i:s',$order->express_time);

        $sender = [];
        $sender["Name"] = $order->deliver_name;
        $sender["Mobile"] = $order->deliver_mobile;
        $sender["ProvinceName"] = $order->deliver_address_province;
        $sender["CityName"] = $order->deliver_address_city;
        $sender["ExpAreaName"] = $order->deliver_address_area;
        $sender["Address"] = $order->deliver_address_detail;

        $receiver = [];
        $receiver["Name"] = "快鱼二手书";
        $receiver["Mobile"] = "15888825922";
        $receiver["ProvinceName"] = "浙江省";
        $receiver["CityName"] = "杭州市";
        $receiver["ExpAreaName"] = "余杭区";
        $receiver["Address"] = "万科未来城二期21-1-2302";

        $commodityOne = [];
        $commodityOne["GoodsName"] = "图书";
        $commodity = [];
        $commodity[] = $commodityOne;

        $eorder["Sender"] = $sender;
        $eorder["Receiver"] = $receiver;
        $eorder["Commodity"] = $commodity;

        //调用在线下单
        $jsonParam = json_encode($eorder, JSON_UNESCAPED_UNICODE);
        $jsonResult = $this->_submitOrder($jsonParam);

        //解析在线下单返回结果
        $result = json_decode($jsonResult, true);
        //print_r($result);die;

        if(($result['Success'] && $result['ResultCode'] == 100))
        {
            $order->update([
                'state'             => 2,
                'is_express'        => 1,
                'express_no'        => $result['Order']['LogisticCode'],
                'shipper_code'      => $result['Order']['ShipperCode'],  //快递公司编码
                'express_order_no'  => $result['Order']['OrderCode'],
                'check_time'        => $this->time,
            ]);

            $sms = app('easysms');
            try {
                $sms->send($order->deliver_mobile,[
                    'template' => 'SMS_163051059',
                    'data' => [
                        'name' => $order->deliver_name,
                        'time' => date('Y-m-d H:i',$order->express_time),
                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                dd($message);
            }

            //发送模板消息
            $officialAccount = EasyWeChat::officialAccount(); // 公众号
            $user = User::query()->select(['id','wechat_openid','unionid'])->where('id',$order->user_id)->first();
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $express_time = date('Y-m-d H:i',$order->express_time);
                $first = "卖书订单通过审核，已安排快递上门取书\r"."顺丰快递将于你预约的时间：{$express_time}免费上门取书。在预约的时间前1小时内您会收到顺丰的短信，请留意短信通知。\r";
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                    'url'  => '',
                    'miniprogram' => [
                        'appid'     => config('wechat.mini_program.default.app_id'),
                        'path'  => '/pages/sale/order/order-detail/order-detail?id='.$order->id,
                    ],
                    'data' => [
                        'first'         => $first,
                        'OrderSn'       => $order->no,
                        'OrderStatus'   => '已安排快递上门取书'."\r\n",
                        'remark'        => '如需修改快递上门时间或订单信息，请取消订单后再重新下单，可在订单详情页进行操作。'
                    ],
                ]);
            }

            return $this->ok([]);
        }

        \Log::debug('kdniao_eorderservice',$result);
        return $this->err(1,200,'','预约快递失败');
    }

    private function _submitOrder($requestData)
    {
        //$url = 'http://testapi.kdniao.cc:8081/api/oorderservice';
        $url = 'http://api.kdniao.com/api/eorderservice';
        $ebusinessid = '1363157';
        $appkey = 'f426aae4-89fa-4a90-863c-08c96328b7f6';
        $datas = array(
            'EBusinessID' => $ebusinessid,
            'RequestType' => '1001',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = kdniao_encrypt($requestData, $appkey);

        $result = sendPost($url, $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }

    private function _cancelOrder($requestData)
    {
        $url = 'http://api.kdniao.com/api/eorderservice';
        $ebusinessid = '1363157';
        $appkey = 'f426aae4-89fa-4a90-863c-08c96328b7f6';
        $datas = array(
            'EBusinessID' => $ebusinessid,
            'RequestType' => '1004',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = kdniao_encrypt($requestData, $appkey);

        //print_r($datas);
        $result = sendPost($url, $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }
}
